package v4

import "fmt"

func (cli *CLI) createBlockChain(address string) {
	NewBlockChain(address)
	fmt.Println("create blockchain successfully!")
}

func (cli *CLI) printChain() {
	blockChain := GetBlockChain()
	if blockChain == nil {
		fmt.Println("printChain fail GetBlockChain !")
		return
	}
	defer blockChain.DB.Close()
	var it = BlockChainIterator{
		blockChain.DB,
		blockChain.TailHash,
	}
	count := 1
	for {
		block := it.Next()
		fmt.Println(" 开始---------------------------------", count)
		fmt.Printf("Version : %d\n", block.Version)
		fmt.Printf("PrevBlockHash : %x\n", block.PreHash)
		fmt.Printf("Hash : %x\n", block.Hash)
		fmt.Printf("MerkleRoot : %x\n", block.MerkleRoot)
		fmt.Printf("TimeStamp : %d\n", block.Timestamp)
		fmt.Printf("Difficuty : %d\n", block.Difficulty)
		fmt.Printf("Nonce : %d\n", block.Nonce)
		for _, transaction := range block.Transactions {
			fmt.Printf("====>TXID : %x\n", transaction.TXID)
			fmt.Printf("IsCoinbase %v\n", transaction.IsCoinbase())
			fmt.Println("---output---")
			for _, output := range transaction.TxOutputs {
				fmt.Printf("output.Value : %f\n", output.Value)
				fmt.Printf("output.ScriptPubKey : %s\n", output.ScriptPubKey)
			}
			fmt.Println("---input---")
			for _, input := range transaction.TxInputs {
				fmt.Printf("input.TxID : %x\n", input.TxID)
				fmt.Printf("input.Index : %d\n", input.Index)
				fmt.Printf("input.Sig : %s\n", input.Sig)
			}
		}
		fmt.Println("结束----------------------------------", count)
		count++
		if len(block.PreHash) == 0 {
			fmt.Println("打印所有区块完成!")
			break
		}
	}
}

func (cli *CLI) getBalance(address string) {
	blockChain := GetBlockChain()
	if blockChain == nil {
		fmt.Println("printChain fail GetBlockChain !")
		return
	}
	defer blockChain.DB.Close()
	balance := blockChain.GetBalance(address)
	fmt.Printf("balance of %s : %f\n", address, balance)
	fmt.Println("getBalance successfully!")
}

// 转账交易
func (cli *CLI) send(from, to, miner string, amount float64) {
	blockChain := GetBlockChain()
	if blockChain == nil {
		fmt.Println("printChain fail GetBlockChain !")
		return
	}
	defer blockChain.DB.Close()
	transaction := NewTransaction(from, to, amount, blockChain)
	coinbaseTransaction := NewCoinbaseTransaction(miner, "挖矿所得")
	blockChain.AddBlock([]*Transaction{transaction, coinbaseTransaction})
	fmt.Println("send successfully!")
}
